package com.bodacn.keypoint;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.pm.PackageManager;
import android.content.res.Configuration;
import android.content.res.Resources;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.media.Ringtone;
import android.media.RingtoneManager;
import android.net.Uri;
import android.os.Build;
import android.os.Environment;
import android.os.Handler;
import android.os.IBinder;
import android.os.Message;
import android.speech.tts.TextToSpeech;
import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentManager;
import androidx.fragment.app.FragmentTransaction;
import androidx.appcompat.app.AppCompatActivity;
import android.os.Bundle;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.Gravity;
import android.view.KeyEvent;
import android.view.View;
import android.view.inputmethod.InputMethodManager;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;

import org.json.JSONArray;
import org.json.JSONException;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.net.InetAddress;
import java.net.MulticastSocket;
import java.sql.Date;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.Timer;
import java.util.TimerTask;

import static android.os.Environment.getExternalStorageDirectory;
import static java.lang.Integer.*;

/**
 * An example full-screen activity that shows and hides the system UI (i.e.
 * status bar and navigation/system bar) with user interaction.
 */
public class MainActivity extends AppCompatActivity implements View.OnClickListener,
        FragmentA.FragmentACallBack,FragmentB.FragmentBCallBack,
        FragmentC.FragmentCCallBack,FragmentE.FragmentECallBack,
        FragmentG.FragmentGCallBack,FragmentScan.FragmentScanCallBack
{
    private final static String TAG = MainActivity.class.getSimpleName();
    public static final int getParamFragmentA = 701;
    public static final int getParamFragmentB = 702;
    public static final int getParamFragmentC = 703;
    public static final int getParamFragmentD = 704;
    public static final int getParamFragmentE = 705;
    public static final int getParamFragmentF = 706;
    public static final int getParamFragmentG = 707;
    public static final int getParamFragmentH = 708;
    public static final int getParamFragmentI = 709;
    public static final int getParamFragmentJ = 710;
    public static final int getParamFragmentK= 711;
    public static final int getParamFragmentL= 712;
    public static final int getParamFragmentM= 713;
    public static final int getParamFragmentN= 714;

    public static final int MSG_TransWeight2FragmentC =8001;
    public static final int MSG_TransRefresh2Fragment =8002;
    public static final int transRuleMsg=8003;
    public static final int MSG_ConnectBlue=8004;
    public static final int MSG_ErrMSG=8005;
    long prScanSec=0;
    TextToSpeech textToSpeech;

    //全局变量
    String SaveFilePath="",SaveDBFolder="/DB";
    public static final String DB_Name ="bdmes.db";
    //全局变量
    String STORE_NAME = "Settings";
    //存放当前Fragment
    private Fragment mContent;
    private FragmentManager fragmentManager=getSupportFragmentManager();

    @Override
    public void FragmentAWorkAndTransParams(Map<String, Object> Params) {
        //根据获取的参数，判断需要执行的事件;
        String paramComm,paramValue;
        //消息约定FragmentIndex，WorkCodeIndex，ParamObject;
        if (Params!=null)
        {
            System.out.println("FragmentAWorkAndTransParams:"+Params);
            //根据参数调用相应功能;
            paramComm=Params.get("ParamComm").toString();
            if (paramComm=="AllowScan")
            {
                paramValue=Params.get("ParamValue").toString();
                Log.d("Main<-"+paramComm,paramValue);
                AllowScan=paramValue.equals("Y");
            }
        }
    }

    @Override
    public void FragmentBWorkAndTransParams(Map<String, Object> Params) {
        //根据获取的参数，判断需要执行的事件;
        String paramComm,paramValue;
        //消息约定FragmentIndex，WorkCodeIndex，ParamObject;
        if (Params!=null)
        {
            System.out.println("FragmentBWorkAndTransParams:"+Params);
            //根据参数调用相应功能;
            paramComm=Params.get("ParamComm").toString();
            if (paramComm=="AllowScan")
            {
                paramValue=Params.get("ParamValue").toString();
                Log.d("Main<-"+paramComm,paramValue);
                AllowScan=paramValue.equals("Y");
            }
        }
    }
    @Override
    public void FragmentScanWorkAndTransParams(Map<String, Object> Params) {
        //根据获取的参数，判断需要执行的事件;
        String paramComm,paramValue;
        //消息约定FragmentIndex，WorkCodeIndex，ParamObject;
        if (Params!=null)
        {
            System.out.println("FragmentScanWorkAndTransParams:"+Params);
            //根据参数调用相应功能;
            paramComm=Params.get("ParamComm").toString();
            if (paramComm=="AllowScan")
            {
                paramValue=Params.get("ParamValue").toString();
                Log.d("Main<-"+paramComm,paramValue);
                AllowScan=paramValue.equals("Y");
            }
        }
    }



    //flie：要删除的文件夹的所在位置
    private void deleteFile(File file) {
        if (file.isDirectory()) {
            File[] files = file.listFiles();
            for (int i = 0; i < files.length; i++) {
                File f = files[i];
                deleteFile(f);
            }
            file.delete();//如要保留文件夹，只删除文件，请注释这行
        } else if (file.exists()) {
            file.delete();
        }
    }

    class FragmentStruct{
        Fragment frgmt;
        String ident;
    }
    private final List<FragmentStruct> mFragments=new ArrayList<FragmentStruct>();//fragment列表;
    int curFragmentIndex = 0;//当前显示页面;
    //服务器地址
    String language="";
    String serviceUrl="http://192.168.10.12/tvservice";
    SQLiteDatabase mainDB;
    String serviceUrlExt  = "/BDService.asmx?wsdl";
    String curLoginUserNo,curLoginUser,curFactory, curDepartNo,curDepart,curLoginTime,CPUID,WorkSection;//操作员所属部门等信息;
    JSONArray curUserPower;
    int curOperateTime =600,SpaceSec=15,SwitchCount=5;//工作分钟
    static int[] WeightArray=new int[10];
    int curPlaceCount=60;//工位数;

    //界面按钮;
    TextView txt_titleInv,txt_funcA,txt_funcB, txt_funcC, txt_funcD, txt_funcE,txt_funcF,txt_funcG,
            txt_funcScan,txt_funcMateSend,txt_funcTransProc,txt_funcTransQuery,txt_funcTransScan;
    TextView title_userNo,title_userName,title_depart,title_logintime,title_power;
    Button btn_LoginUser, btn_LoginClose;

    Toast curToast;
    private ProgressDialog waitDialog = null;
    //用于将Activity中的参数传给Fragment
    private Map<String,Object> loginParams=new HashMap<String,Object>();
    static boolean receiveFlag=false;
    static boolean haveCardNo=false;
    static FileInputStream mInputStream = null;
    static boolean ExitRun=false;
    static String CardNo="";
    static boolean AllowRepeat=true;
    static boolean AllowScan=true;
    static int baudrate=9600;
    static int parity=0;
    String PrWeight="";
    private boolean mBtOpenSilent = true;
    private BluetoothAdapter btAdapter = null;
    //初始化定时器;
    private Timer timer;
    private TimerTask timetask;
    //广播消息
    /*接收广播端的socket*/
    private MulticastSocket socket;
    private int udpPort=40000;
    String multicastHost="224.0.0.1";//广播地址;
    InetAddress receiveAddress;
    private boolean NeedBlueTooth=false;
    //拦截扫描枪输入部分
    String BarcodeStr="";
    ScannerManager scannerManager;
    //FragmentC回调;

    @Override
    public void FragmentCWorkAndTransParams(Map<String, Object> Params) {
        //根据获取的参数，判断需要执行的事件;
        String paramComm,paramValue;
        //消息约定FragmentIndex，WorkCodeIndex，ParamObject;
        if (Params!=null)
        {
            System.out.println("FragmentCWorkAndTransParams:"+Params);
            //根据参数调用相应功能;
            paramComm=Params.get("ParamComm").toString();
            if (paramComm=="AllowScan")
            {
                paramValue=Params.get("ParamValue").toString();
                Log.d("Main<-"+paramComm,paramValue);
                AllowScan=paramValue.equals("Y");
            }
            //根据参数调用相应功能;
            paramComm=Params.get("ParamComm").toString();
            //进入工序分配界面;
            if (paramComm=="Speech")
            {
                paramValue=Params.get("Text").toString();
                textToSpeech.speak(paramValue, TextToSpeech.QUEUE_FLUSH, null);
            }

        }
    }
    @Override
    public void FragmentGWorkAndTransParams(Map<String, Object> Params) {
        //根据获取的参数，判断需要执行的事件;
        String paramComm,paramValue;
        //消息约定FragmentIndex，WorkCodeIndex，ParamObject;
        if (Params!=null)
        {
            //根据参数调用相应功能;
            paramComm=Params.get("ParamComm").toString();
            //根据参数调用相应功能;
            if (paramComm=="AllowScan")
            {
                paramValue=Params.get("ParamValue").toString();
                Log.d("Main<-"+paramComm,paramValue);
                AllowScan=paramValue.equals("Y");
            }
            //进入工序分配界面;
            if (paramComm=="Speech")
            {
                paramValue=Params.get("Text").toString();
                textToSpeech.speak(paramValue, TextToSpeech.QUEUE_FLUSH, null);
            }

        }
    }

    //创建数据库表
    private void CreateDBTable(){
        if (mainDB!=null) {
            //建表语句;
            //建表语句;
            //软件版本;
            mainDB.execSQL("CREATE TABLE IF NOT EXISTS SoftVer (ID INTEGER PRIMARY KEY AUTOINCREMENT,CurSoftVer varchar(30))");

            mainDB.execSQL("CREATE TABLE IF NOT EXISTS QCQuestion (ID INTEGER PRIMARY KEY AUTOINCREMENT,QuestionNo VARCHAR,QuestionCode VARCHAR,TypeIndex int,QuestionType VARCHAR)");
            mainDB.execSQL("CREATE TABLE IF NOT EXISTS PartDefine (ID INTEGER PRIMARY KEY AUTOINCREMENT,PartName VARCHAR,PosX REAL,PosY REAL)");
            //员工表;
            mainDB.execSQL("CREATE TABLE IF NOT EXISTS EmpList (ID INTEGER PRIMARY KEY AUTOINCREMENT,DepartNo VARCHAR,EmpID VARCHAR,EmpNo VARCHAR, EmpName VARCHAR,EmpCT NUMERIC(8,2))");
            //员工工序表;
            mainDB.execSQL("CREATE TABLE IF NOT EXISTS EmpProcList (ID INTEGER PRIMARY KEY AUTOINCREMENT,DepartNo VARCHAR,EmpNo VARCHAR,EmpName VARCHAR,OrderNo VARCHAR,StyleNo VARCHAR,StyleID VARCHAR," +
                    "StyleProID VARCHAR,StyleSort VARCHAR,WorkDate VARCHAR,WorkLineNo INTEGER,WorkNo VARCHAR,WorkName VARCHAR,MachineName VARCHAR,SlowTime INT,PlaceNo INT)");
            //工序表;
            mainDB.execSQL("CREATE TABLE IF NOT EXISTS ProcList (ID INTEGER PRIMARY KEY AUTOINCREMENT,DepartNo VARCHAR,OrderNo VARCHAR,StyleNo VARCHAR,StyleID VARCHAR,StyleSort VARCHAR,WorkDate VARCHAR,ArrangeID VARCHAR,SchemeID VARCHAR,ArrangeDeID VARCHAR,StyleProID VARCHAR," +
                    "PartIndex INTEGER,Part VARCHAR, WorkLineNo INTEGER,WorkNo VARCHAR,WorkName VARCHAR,MachineName VARCHAR,SlowTime INTEGER,WorkCT NUMERIC(8,2),WorkArrEmps VARCHAR,WorkArrEmpNos VARCHAR,PlaceNos VARCHAR,PlanEmpNum INTEGER,BaseKey VARCHAR)");
            //工序主表;
            mainDB.execSQL("CREATE TABLE IF NOT EXISTS ProcMaList (ID INTEGER PRIMARY KEY AUTOINCREMENT,ArrangeID VARCHAR,DepartNo VARCHAR,OrderNo VARCHAR,StyleNo VARCHAR,StyleID VARCHAR,StyleSort VARCHAR,WorkDate VARCHAR,OrderNumber INTEGER,SAMValue NUMERIC(8,2),TargetNum INTEGER,TT INTEGER," +
                    "CT NUMERIC(8,2),EmpCount INTEGER,BudgetOut INTEGER,BalanceRatio NUMERIC(8,2),PlaceCount INTEGER,UpdateTime DATETIME)");
            //临时表;
            mainDB.execSQL("CREATE TABLE IF NOT EXISTS EmpTotalCT (ID INTEGER PRIMARY KEY AUTOINCREMENT,DepartNo VARCHAR,EmpNo VARCHAR,OrderNo VARCHAR,StyleNo VARCHAR,StyleID VARCHAR,EmpCT NUMERIC(8,2))");
            mainDB.execSQL("CREATE TABLE IF NOT EXISTS EmpTotalCount (ID INTEGER PRIMARY KEY AUTOINCREMENT,DepartNo VARCHAR,OrderNo VARCHAR,StyleNo VARCHAR,StyleID VARCHAR,StyleProID VARCHAR,WorkNo VARCHAR,EmpCount INTEGER)");
            //主界面订单信息表;
            mainDB.execSQL("CREATE TABLE IF NOT EXISTS OrderList (ID INTEGER PRIMARY KEY AUTOINCREMENT,StartDate VARCHAR,DepartmentNo VARCHAR,Department VARCHAR,OrderNo VARCHAR,StyleNo VARCHAR,StyleSort VARCHAR,StyleID VARCHAR,Number INTEGER,SAMValue NUMERIC(8,2),TargetNum INTEGER," +
                    "TT INTEGER,StyleProcID VARCHAR,WorkNo VARCHAR,WorkName VARCHAR,TotalSew INTEGER, TotalCheck INTEGER,TotalOver INTEGER,CurSew INTEGER, CurCheck INTEGER,CurOver INTEGER,SelSign BOOLEAN,UpdateTime DATETIME,UserNo VARCHAR)");
            //保存最后在处理的合约信息;
            mainDB.execSQL("CREATE TABLE IF NOT EXISTS LastAssayInfo (ID INTEGER PRIMARY KEY AUTOINCREMENT, LoginNo VARCHAR,LoginUser VARCHAR,Factory VARCHAR,DepartNo VARCHAR,DepartName VARCHAR,PeopleNum INT,WorkTime INTEGER,LastUpTime DATETIME)");
            //临时表用于暂存数据;
            mainDB.execSQL("CREATE TABLE IF NOT EXISTS DayNumList(ID INTEGER PRIMARY KEY AUTOINCREMENT,DayTitle VARCHAR,DayNum INT)");
            //读取配置文件;
            mainDB.execSQL("CREATE TABLE IF NOT EXISTS SetupTable (ID INTEGER PRIMARY KEY AUTOINCREMENT, KeyName VARCHAR,KeyValue VARCHAR)");
            //机台安排表;
            mainDB.execSQL("CREATE TABLE IF NOT EXISTS ArrangeMachine (ID INTEGER PRIMARY KEY AUTOINCREMENT,PlaceNo INT,EmpID VARCHAR,EmpNo VARCHAR,EmpName VARCHAR,WorkNames VARCHAR,MachineName VARCHAR,ConColor VARCHAR)");
            //部件及疵点表;
            mainDB.execSQL("CREATE TABLE IF NOT EXISTS PartQuestion (ID INTEGER PRIMARY KEY AUTOINCREMENT,PartNo VARCHAR,PartName VARCHAR,QuestionNo VARCHAR,QuestionName VARCHAR)");
            //报帐表;
            mainDB.execSQL("CREATE TABLE IF NOT EXISTS DaliyMa (ID INTEGER PRIMARY KEY AUTOINCREMENT,DepartNo VARCHAR,WorkDate VARCHAR,OrderNo VARCHAR,StyleNo VARCHAR,StyleSort VARCHAR)");
            mainDB.execSQL("CREATE TABLE IF NOT EXISTS DaliyCount (ID INTEGER PRIMARY KEY AUTOINCREMENT,EmpOperNumID VARCHAR,RowNo int,EmpID VARCHAR,EmpNo VARCHAR,EmpName VARCHAR,WorkNo int," +
                    "WorkName VARCHAR,SewNum int,OverNum int,DaySewNum int,DayOverNum int,AccountNum int,RemainNum int,RptNum int,LockState varchar,EditFlag varchar,TotalReal int,ErrorSign int)");
            //转移印工序分解
            mainDB.execSQL("CREATE TABLE IF NOT EXISTS TransProcSon (ID INTEGER PRIMARY KEY AUTOINCREMENT,RowNo int,SonSerial int,PrWorkNo VARCHAR,WorkNo VARCHAR,WorkName VARCHAR,SAM NUMERIC(8,2),RealValue NUMERIC(8,3))");
        }

    }
    //删除数据库
    private void dropAllTable(){
        if (mainDB!=null) {
            Log.d("Delete","删除数据库！");
            mainDB.execSQL("DROP TABLE IF EXISTS QCQuestion");
            mainDB.execSQL("DROP TABLE IF EXISTS PartDefine");
            Log.d("Delete","删除数据库！");
            mainDB.execSQL("DROP TABLE IF EXISTS EmpList");
            mainDB.execSQL("DROP TABLE IF EXISTS EmpProcList");
            mainDB.execSQL("DROP TABLE IF EXISTS ProcList");
            mainDB.execSQL("DROP TABLE IF EXISTS EmpTotalCT");
            mainDB.execSQL("DROP TABLE IF EXISTS EmpTotalCount");
            mainDB.execSQL("DROP TABLE IF EXISTS ProcMaList");
            mainDB.execSQL("DROP TABLE IF EXISTS OrderList");
            mainDB.execSQL("DROP TABLE IF EXISTS SetupTable");
            mainDB.execSQL("DROP TABLE IF EXISTS LastAssayInfo");
            mainDB.execSQL("DROP TABLE IF EXISTS ArrangeMachine");
            mainDB.execSQL("DROP TABLE IF EXISTS PartQuestion");
            mainDB.execSQL("DROP TABLE IF EXISTS DaliyMa");
            mainDB.execSQL("DROP TABLE IF EXISTS DaliyCount");
            mainDB.execSQL("DROP TABLE IF EXISTS TransProcSon");
            curToast.setText("数据删除成功,请退出重新进入！");
            curToast.show();
        } else System.out.println("外部存储不可读写！");
    }


    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        //左右翻页;
        System.out.println("keyCode:"+keyCode);
        if (keyCode==24) {
            //发送消息到C类;
            sendParamFragmentCWeight("0");
            return true;
        }
        return super.onKeyDown(keyCode, event);
    }

    //FragmentE回调;
    @Override
    public void FragmentEWorkAndTransParams(Map<String, Object> Params) {
        //根据获取的参数，判断需要执行的事件;
        String paramComm,paramValue;
        //消息约定FragmentIndex，WorkCodeIndex，ParamObject;
        if (Params!=null)
        {
            //根据参数调用相应功能;
            paramComm=Params.get("ParamComm").toString();
            if (paramComm=="AllowScan")
            {
                paramValue=Params.get("ParamValue").toString();
                Log.d("Main<-"+paramComm,paramValue);
                AllowScan=paramValue.equals("Y");
            }
            //进入工序分配界面;
            if (paramComm=="CardNo")
            {
                paramValue=Params.get("ParamValue").toString();
                Log.d("Main<-"+paramComm,paramValue);
                haveCardNo=true;
                CardNo=paramValue;
                Log.d("CardNo:",CardNo);
            }
            if (paramComm=="Repeat")
            {
                paramValue=Params.get("ParamValue").toString();
                Log.d("Main<-"+paramComm,paramValue);
                AllowRepeat=paramValue.equals("T");
            }


        }
    }



    //启动定时器;
    private void startTimer(){
        if (timer == null) {
            timer = new Timer();
        }
        //定时任务;
        if (timetask == null) {
            timetask = new TimerTask() {
                @Override
                public void run() {
                    //也可发消息，由Handler负责统一调度执行;
                    Message message = new Message();
                    message.what = MSG_TransRefresh2Fragment;
                    mainHandler.sendMessage(message);
                }
            };
            timer.schedule(timetask, SpaceSec*1000, SpaceSec*1000);
        }
        System.out.println("startTimer One---------------------------------Start");
    }

    //停止计时器;
    private void stopTimer(){
        if (timer != null) {
            timer.cancel();
            timer = null;
        }
        if (timetask != null) {
            timetask.cancel();
            timetask = null;
        }
        if (waitDialog!=null) waitDialog.dismiss();
        System.out.println("startTimer One---------------------------------Start");
    }


    //接收线程消息;
    private final Handler mHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            System.out.println("handleMessage:"+msg);
            int hi,low;
            switch (msg.what) {
                case MSG_ErrMSG:
                    Bundle bundle=msg.getData();
                    if (bundle!=null) {
                        curToast.setText(bundle.getString("MSG"));
                        curToast.show();
                    }
                    break;
                case MSG_ConnectBlue:
                    break;
                case transRuleMsg:
                    Bundle bdl=msg.getData();
                    if (bdl!=null) {
                        byte[] recdata = bdl.getByteArray("recData");
                        int len = bdl.getInt("len");
                        transRule(recdata, len);
                    }
                    break;
                default:
                    break;
            }
        }
    };

    //转换并传递
    private void transRule(byte[] recData,int len){
        //解析尺寸并输出;
        if (len==8){
            if ((recData[6]==(byte)0xFF)&&(recData[7]==(byte)0xFF)) {
                String s = bytesToHexs(recData, len);
                System.out.println("Enter ready Out");
                int code = Integer.parseInt("8D6A", 16);
                int length = Integer.parseInt(s.substring(0, 4), 16);
                int angle = Integer.parseInt(s.substring(4, 8), 16);
                int battery = Integer.parseInt(s.substring(8, 12), 16);
                int a1 = length ^ code;
                int a2 = angle ^ code;
                int a3 = battery ^ code;
                if (transParamsListenerG != null) {
                    Log.d("SendParam", "sendParamFragmentG------------------1;");
                    Map<String,Object> tmpParams=new HashMap<String,Object>();
                    tmpParams.put("ParamComm", "BlueParam");
                    tmpParams.put("lenght",a1);
                    tmpParams.put("power",a3);
                    title_power.setText(String.valueOf(a3)+"%");
                    transParamsListenerG.TransParams(tmpParams);
                    Log.d("SendParam", "transParamsListenerG------------------2;");
                }
            }
        }
    }

    private static String bytesToHexs(byte[] bytes,int size) {
        StringBuilder sb = new StringBuilder();
        //for (int i = 0; i < bytes.length; i++) {
        for (int i = 0; i < size; i++) {
            String hex = toHexString(0xFF & bytes[i]).toUpperCase();
            if (hex.length() == 1) {
                sb.append('0');
            }
            sb.append(hex);
        }
        return sb.toString();
    }
    /**
     * 计算CRC16校验码*
     * @param bytes 字节数组
     * @return {@linkstring} 校验码
     * @since 1.0
     */
    public static int getCRC(byte[] bytes,int len) {
        int CRC = 0x0000ffff;
        int POLYNOMIAL = 0x0000a001;
        int i, j;
        for (i = 0; i < len; i++) {
            CRC ^= ((int) bytes[i] & 0x000000ff);
            for (j = 0; j < 8; j++) {
                if ((CRC & 0x00000001) != 0) {
                    CRC >>= 1;
                    CRC ^= POLYNOMIAL;
                } else {
                    CRC >>= 1;
                }
            }
        }
        return CRC;
    }
    /**
     * byte[]数组转换为16进制的字符串
     *
     * @param bytes 要转换的字节数组
     * @return 转换后的结果
     */
    private static String bytesToHexString(byte[] bytes,int size) {
        StringBuilder sb = new StringBuilder();
        //for (int i = 0; i < bytes.length; i++) {
        for (int i = 0; i < size; i++) {
            String hex = toHexString(0xFF & bytes[i]).toUpperCase();
            if (hex.length() == 1) {
                sb.append('0');
            }
            sb.append(hex+" ");
        }
        return sb.toString();
    }

    /**
     * 将byte转换为一个长度为8的byte数组，数组每个值代表bit
     */
    public static byte[] getBitArray(byte b) {
        byte[] array = new byte[8];
        for (int i = 7; i >= 0; i--) {
            array[i] = (byte)(b & 1);
            b = (byte) (b >> 1);
        }
        return array;
    }
    /**
     * 把byte转为字符串的bit
     */
    public static String byteToBit(byte b) {
        return ""
                + (byte) ((b >> 7) & 0x1) + (byte) ((b >> 6) & 0x1)
                + (byte) ((b >> 5) & 0x1) + (byte) ((b >> 4) & 0x1)
                + (byte) ((b >> 3) & 0x1) + (byte) ((b >> 2) & 0x1)
                + (byte) ((b >> 1) & 0x1) + (byte) ((b >> 0) & 0x1);
    }



    //---------------------------接口申明及调用------------------------开始;
    //A:定义一个传参接口;
    public  interface OnTransParamsListenerA{
        // 里面传个值@param Map<String,Object>适应多种类型;
        public void TransParams(Map<String, Object> mParams);
    }
    //2:对外公开的transParamsListener事件,配合接口及对外公布的事件;
    private OnTransParamsListenerA transParamsListenerA;
    //3:写一个对外公开的方法setTransParamsListener,供Fragment加接口监使用;
    public void setTransParamsListenerA(OnTransParamsListenerA transParamsListener){
        this.transParamsListenerA=transParamsListener;
    }
    //B:定义一个传参接口;
    public  interface OnTransParamsListenerB{
        // 里面传个值@param Map<String,Object>适应多种类型;
        public void TransParams(Map<String, Object> mParams);
    }
    //2:对外公开的transParamsListener事件,配合接口及对外公布的事件;
    private OnTransParamsListenerB transParamsListenerB;
    //3:写一个对外公开的方法setTransParamsListener,供Fragment加接口监使用;
    public void setTransParamsListenerB(OnTransParamsListenerB transParamsListener){
        this.transParamsListenerB=transParamsListener;
    }
    //C:定义一个传参接口;
    public  interface OnTransParamsListenerC{
        // 里面传个值@param Map<String,Object>适应多种类型;
        public void TransParams(Map<String, Object> mParams);
    }
    //2:对外公开的transParamsListener事件,配合接口及对外公布的事件;
    private OnTransParamsListenerC transParamsListenerC;
    //3:写一个对外公开的方法setTransParamsListener,供Fragment加接口监使用;
    public void setTransParamsListenerC(OnTransParamsListenerC transParamsListener){
        this.transParamsListenerC=transParamsListener;
    }
    //D:定义一个传参接口;
    public  interface OnTransParamsListenerD{
        // 里面传个值@param Map<String,Object>适应多种类型;
        public void TransParams(Map<String, Object> mParams);
    }
    //2:对外公开的transParamsListener事件,配合接口及对外公布的事件;
    private OnTransParamsListenerD transParamsListenerD;
    //3:写一个对外公开的方法setTransParamsListener,供Fragment加接口监使用;
    public void setTransParamsListenerD(OnTransParamsListenerD transParamsListener){
        this.transParamsListenerD=transParamsListener;
    }
    //E:定义一个传参接口;
    public  interface OnTransParamsListenerE{
        // 里面传个值@param Map<String,Object>适应多种类型;
        public void TransParams(Map<String, Object> mParams);
    }
    //2:对外公开的transParamsListener事件,配合接口及对外公布的事件;
    private OnTransParamsListenerE transParamsListenerE;
    //3:写一个对外公开的方法setTransParamsListener,供Fragment加接口监使用;
    public void setTransParamsListenerE(OnTransParamsListenerE transParamsListener){
        this.transParamsListenerE=transParamsListener;
    }
    //F定义一个传参接口;
    public  interface OnTransParamsListenerF{
        // 里面传个值@param Map<String,Object>适应多种类型;
        public void TransParams(Map<String, Object> mParams);
    }
    //2:对外公开的transParamsListener事件,配合接口及对外公布的事件;
    private OnTransParamsListenerF transParamsListenerF;
    //3:写一个对外公开的方法setTransParamsListener,供Fragment加接口监使用;
    public void setTransParamsListenerF(OnTransParamsListenerF transParamsListener){
        this.transParamsListenerF=transParamsListener;
    }
    //G定义一个传参接口;
    public  interface OnTransParamsListenerG{
        // 里面传个值@param Map<String,Object>适应多种类型;
        public void TransParams(Map<String, Object> mParams);
    }
    //2:对外公开的transParamsListener事件,配合接口及对外公布的事件;
    private OnTransParamsListenerG transParamsListenerG;
    //3:写一个对外公开的方法setTransParamsListener,供Fragment加接口监使用;
    public void setTransParamsListenerG(OnTransParamsListenerG transParamsListener){
        this.transParamsListenerG=transParamsListener;
    }
    //H定义一个传参接口;
    public  interface OnTransParamsListenerH{
        // 里面传个值@param Map<String,Object>适应多种类型;
        public void TransParams(Map<String, Object> mParams);
    }
    //2:对外公开的transParamsListener事件,配合接口及对外公布的事件;
    private OnTransParamsListenerH transParamsListenerH;
    //3:写一个对外公开的方法setTransParamsListener,供Fragment加接口监使用;
    public void setTransParamsListenerH(OnTransParamsListenerH transParamsListener){
        this.transParamsListenerH=transParamsListener;
    }
    //I定义一个传参接口;
    public  interface OnTransParamsListenerI{
        // 里面传个值@param Map<String,Object>适应多种类型;
        public void TransParams(Map<String, Object> mParams);
    }
    //2:对外公开的transParamsListener事件,配合接口及对外公布的事件;
    private OnTransParamsListenerI transParamsListenerI;
    //3:写一个对外公开的方法setTransParamsListener,供Fragment加接口监使用;
    public void setTransParamsListenerI(OnTransParamsListenerI transParamsListener){
        this.transParamsListenerI=transParamsListener;
    }
    //J定义一个传参接口;
    public  interface OnTransParamsListenerJ{
        // 里面传个值@param Map<String,Object>适应多种类型;
        public void TransParams(Map<String, Object> mParams);
    }
    //2:对外公开的transParamsListener事件,配合接口及对外公布的事件;
    private OnTransParamsListenerJ transParamsListenerJ;
    //3:写一个对外公开的方法setTransParamsListener,供Fragment加接口监使用;
    public void setTransParamsListenerJ(OnTransParamsListenerJ transParamsListener){
        this.transParamsListenerJ=transParamsListener;
    }
    //K定义一个传参接口;
    public  interface OnTransParamsListenerK{
        // 里面传个值@param Map<String,Object>适应多种类型;
        public void TransParams(Map<String, Object> mParams);
    }
    //2:对外公开的transParamsListener事件,配合接口及对外公布的事件;
    private OnTransParamsListenerK transParamsListenerK;
    //3:写一个对外公开的方法setTransParamsListener,供Fragment加接口监使用;
    public void setTransParamsListenerK(OnTransParamsListenerK transParamsListener){
        this.transParamsListenerK=transParamsListener;
    }
    //K定义一个传参接口;
    public  interface OnTransParamsListenerL{
        // 里面传个值@param Map<String,Object>适应多种类型;
        public void TransParams(Map<String, Object> mParams);
    }
    //2:对外公开的transParamsListener事件,配合接口及对外公布的事件;
    private OnTransParamsListenerL transParamsListenerL;
    //3:写一个对外公开的方法setTransParamsListener,供Fragment加接口监使用;
    public void setTransParamsListenerL(OnTransParamsListenerL transParamsListener){
        this.transParamsListenerL=transParamsListener;
    }
    //K定义一个传参接口;
    public  interface OnTransParamsListenerM{
        // 里面传个值@param Map<String,Object>适应多种类型;
        public void TransParams(Map<String, Object> mParams);
    }
    //2:对外公开的transParamsListener事件,配合接口及对外公布的事件;
    private OnTransParamsListenerM transParamsListenerM;
    //3:写一个对外公开的方法setTransParamsListener,供Fragment加接口监使用;
    public void setTransParamsListenerM(OnTransParamsListenerM transParamsListener){
        this.transParamsListenerM=transParamsListener;
    }
    //K定义一个传参接口;
    public  interface OnTransParamsListenerN{
        // 里面传个值@param Map<String,Object>适应多种类型;
        public void TransParams(Map<String, Object> mParams);
    }
    //2:对外公开的transParamsListener事件,配合接口及对外公布的事件;
    private OnTransParamsListenerN transParamsListenerN;
    //3:写一个对外公开的方法setTransParamsListener,供Fragment加接口监使用;
    public void setTransParamsListenerN(OnTransParamsListenerN transParamsListener){
        this.transParamsListenerN=transParamsListener;
    }
    //K定义一个传参接口;
    public  interface OnTransParamsListenerO{
        // 里面传个值@param Map<String,Object>适应多种类型;
        public void TransParams(Map<String, Object> mParams);
    }
    //2:对外公开的transParamsListener事件,配合接口及对外公布的事件;
    private OnTransParamsListenerO transParamsListenerO;
    //3:写一个对外公开的方法setTransParamsListener,供Fragment加接口监使用;
    public void setTransParamsListenerO(OnTransParamsListenerO transParamsListener){
        this.transParamsListenerO=transParamsListener;
    }

    //---------------------------2、明细界面接口申明及调用------------------------开始;
    //1:定义一个传参接口;
    public  interface OnTransParamsListenerScanNC {
        // 里面传个值@param Map<String,Object>适应多种类型;
        public void TransParams(Map<String,Object> mParams);
    }
    //2:对外公开的transParamsListener事件,配合接口及对外公布的事件;
    private OnTransParamsListenerScanNC transParamsListenerScan;
    //3:写一个对外公开的方法setTransParamsListener,供Fragment加接口监使用;
    public void setTransParamsListenerScan(OnTransParamsListenerScanNC transParamsListenerScan){
        this.transParamsListenerScan = transParamsListenerScan;
    }
    //---------------------------2、明细接口申明及调用------------------------结束;
    //---------------------------2、明细界面接口申明及调用------------------------开始;
    //1:定义一个传参接口;
    public  interface OnTransParamsListenerMateSend {
        // 里面传个值@param Map<String,Object>适应多种类型;
        public void TransParams(Map<String,Object> mParams);
    }
    //2:对外公开的transParamsListener事件,配合接口及对外公布的事件;
    private OnTransParamsListenerMateSend transParamsListenerMateSend;
    //3:写一个对外公开的方法setTransParamsListener,供Fragment加接口监使用;
    public void setTransParamsListenerMateSend(OnTransParamsListenerMateSend transParamsListenerMateSend){
        this.transParamsListenerMateSend = transParamsListenerMateSend;
    }
    //---------------------------2、明细接口申明及调用------------------------结束;
    //---------------------------2、明细界面接口申明及调用------------------------开始;
    //1:定义一个传参接口;
    public  interface OnTransParamsListenerTransProc {
        // 里面传个值@param Map<String,Object>适应多种类型;
        public void TransParams(Map<String,Object> mParams);
    }
    //2:对外公开的transParamsListener事件,配合接口及对外公布的事件;
    private OnTransParamsListenerTransProc transParamsListenerTransProc;
    //3:写一个对外公开的方法setTransParamsListener,供Fragment加接口监使用;
    public void setTransParamsListenerTransProc(OnTransParamsListenerTransProc transParamsListenerTransProc){
        this.transParamsListenerTransProc = transParamsListenerTransProc;
    }
    //---------------------------2、明细接口申明及调用------------------------结束;
    //---------------------------2、明细界面接口申明及调用------------------------开始;
    //1:定义一个传参接口;
    public  interface OnTransParamsListenerTransQuery {
        // 里面传个值@param Map<String,Object>适应多种类型;
        public void TransParams(Map<String,Object> mParams);
    }
    //2:对外公开的transParamsListener事件,配合接口及对外公布的事件;
    private OnTransParamsListenerTransQuery transParamsListenerTransQuery;
    //3:写一个对外公开的方法setTransParamsListener,供Fragment加接口监使用;
    public void setTransParamsListenerTransQuery(OnTransParamsListenerTransQuery transParamsListenerTransQuery){
        this.transParamsListenerTransQuery = transParamsListenerTransQuery;
    }
    //---------------------------2、明细接口申明及调用------------------------结束;
    //---------------------------2、明细界面接口申明及调用------------------------开始;
    //1:定义一个传参接口;
    public  interface OnTransParamsListenerTransScan {
        // 里面传个值@param Map<String,Object>适应多种类型;
        public void TransParams(Map<String,Object> mParams);
    }
    //2:对外公开的transParamsListener事件,配合接口及对外公布的事件;
    private OnTransParamsListenerTransScan transParamsListenerTransScan;
    //3:写一个对外公开的方法setTransParamsListener,供Fragment加接口监使用;
    public void setTransParamsListenerTransScan(OnTransParamsListenerTransScan transParamsListenerTransScan){
        this.transParamsListenerTransScan = transParamsListenerTransScan;
    }
    //---------------------------2、明细接口申明及调用------------------------结束;
    //核心设置的代码
    protected void switchLanguage() {
        //读取配置文件-设置语言
        SharedPreferences settings = getSharedPreferences(STORE_NAME, MODE_PRIVATE);
        serviceUrl=settings.getString("serviceUrl",serviceUrl);
        language=settings.getString("language",language);
        //获取资源
        Resources resources = getResources();
        Configuration config = resources.getConfiguration();
        DisplayMetrics dm = resources.getDisplayMetrics();
        switch (language) {
            case "zh":
                config.locale = new Locale("zh","");
                resources.updateConfiguration(config, dm);
                break;
            case "en":
                config.locale = new Locale("en","");
                resources.updateConfiguration(config, dm);
                break;
            case "km":
                config.locale = new Locale("km","");
                resources.updateConfiguration(config, dm);
                break;
            default:
                config.locale = new Locale("zh","");
                resources.updateConfiguration(config, dm);
                break;
        }
    }


    class TTSListener implements TextToSpeech.OnInitListener {
        @Override
        public void onInit(int status) {
            // TODO Auto-generated method stub
            if (status == TextToSpeech.SUCCESS) {
                System.out.println("onInit: TTS引擎初始化成功");
            }
            else{
                System.out.println("onInit: TTS引擎初始化失败");
            }
        }
    }

    @Override
    public boolean dispatchKeyEvent(KeyEvent event) {
        if (scannerManager.dispatchKeyEvent(event)) {
            return true;
        }
        return super.dispatchKeyEvent(event);
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        deleteFile(getCacheDir());
        //设置语言;
        switchLanguage();
        //语音播报;
        //voice_speed:最快语速1.5";
        //voice_pitch:最高音调2.0";
        textToSpeech=new TextToSpeech(this,new TTSListener());
        textToSpeech.setPitch(1.5f); // 在系统设置里也可以修改音调
        //打开或创建数据库文件;
        mainDB = openOrCreateDatabase(DB_Name, this.MODE_PRIVATE, null);
        //创建目录;
        try{
            //取存储路径;
            if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {
                //SD卡准备好的话，优先存储;
                SaveFilePath = getExternalStorageDirectory().toString();
                Log.d("msg","用存储卡:"+SaveFilePath);
            }
            else{
                //系统内部Flash;
                SaveFilePath =this.getFilesDir().toString();
                Log.d("msg","用系统目录:"+SaveFilePath);
            }
            //组织并判断是否需要创建Root目录;
            SaveFilePath = SaveFilePath +"/BDMES";
            Log.d("msg","存储目录为:"+SaveFilePath);
            //判断是否需要创建BDMES根目录;
            if (isExternalStorageWritable()==true) {
                //主目录;
                File file = new File(SaveFilePath);
                if (!file.isDirectory()) file.mkdir();
                Log.d("msg","目录创建成功:"+ SaveFilePath );
                //数据库目录
                file = new File(SaveFilePath +SaveDBFolder);
                if (!file.isDirectory()) file.mkdir();
                Log.d("msg","目录创建成功:"+ SaveFilePath +SaveDBFolder);
            }
            //设置页面;
            setContentView(R.layout.activity_main);
            //获取登陆参数
            Bundle paramBundle = this.getIntent().getExtras();
            curLoginUserNo=paramBundle.getString("LoginUserNo");
            curLoginUser=paramBundle.getString("LoginUser");
            curLoginTime=paramBundle.getString("LoginTime");
            curFactory=paramBundle.getString("CurFactory");
            curDepartNo=paramBundle.getString("CurDepartNo");
            curDepart=paramBundle.getString("CurDepart");
            curPlaceCount=paramBundle.getInt("PlaceCount");
            curOperateTime=paramBundle.getInt("OperateTime");
            serviceUrl=paramBundle.getString("serviceUrl");
            serviceUrlExt=paramBundle.getString("serviceUrlExt");
            CPUID=paramBundle.getString("CPUID");
            SpaceSec=paramBundle.getInt("SpaceSec");
            SwitchCount=paramBundle.getInt("SwitchCount");
            WorkSection=paramBundle.getString("WorkSection");
            curUserPower=new JSONArray(paramBundle.getString("UserPower"));

            System.out.println(paramBundle);
            //最少30秒刷新一次
            if (SpaceSec<30) SpaceSec=30;
            //暂存Login参数;
            loginParams.clear();
            loginParams.put("ParamComm", "LoginParam");
            loginParams.put("LoginUserNo", curLoginUserNo);
            loginParams.put("LoginUser", curLoginUser);
            loginParams.put("DepartNo", curDepartNo);
            loginParams.put("Depart", curDepart);
            loginParams.put("Factory", curFactory);
            loginParams.put("CPUID",CPUID);
            loginParams.put("PlaceCount",curPlaceCount);
            loginParams.put("OperateTime",curOperateTime);
            loginParams.put("ServiceUrl",serviceUrl+serviceUrlExt);
            loginParams.put("ServiceDir",serviceUrl);
            loginParams.put("SpaceSec",SpaceSec);
            loginParams.put("SwitchCount",SwitchCount);
            loginParams.put("WorkSection",WorkSection);
            System.out.println("onCreate ------------------------setText---------2.3");
            //提示框pd=new ProgressDialog(this);
            waitDialog= new ProgressDialog(this);
            waitDialog.setTitle(getString(R.string.SystemHint));
            //接收广播
            try {
                System.out.println("初始化广播发送");
                socket = new MulticastSocket(udpPort);
                receiveAddress=InetAddress.getByName(multicastHost);
                socket.joinGroup(receiveAddress);//加入广播组
            } catch (Exception e1) {
                // TODO Auto-generated catch block
                e1.printStackTrace();
            }
        } catch (Exception e){
            Toast.makeText(this,String.valueOf("出错了，"+e.getMessage()),Toast.LENGTH_LONG).show();
        }
        System.out.println("onCreate:A");
        //全屏
        hideBottomUIMenu();
        //初始化按键，并将页面加载到fragment列表中;
        System.out.println("onCreate:B");
        initView();


        //显示登陆员工;
        btn_LoginUser.setText(curLoginUser);
        title_userNo.setText(curLoginUserNo);
        title_userName.setText(curLoginUser);
        title_depart.setText(curDepart+" ["+curDepartNo+"]");
        title_logintime.setText(curLoginTime);

        System.out.println("curUserPower:"+curUserPower);
        if (curUserPower!=null)
        {
            txt_funcA.setVisibility(View.GONE);
            txt_funcB.setVisibility(View.GONE);
            txt_funcC.setVisibility(View.GONE);
            txt_funcD.setVisibility(View.GONE);
            txt_funcE.setVisibility(View.GONE);
            txt_funcF.setVisibility(View.GONE);
            txt_funcG.setVisibility(View.GONE);
            txt_funcMateSend.setVisibility(View.GONE);
            txt_funcTransProc.setVisibility(View.GONE);
            txt_funcTransQuery.setVisibility(View.GONE);
            txt_funcTransScan.setVisibility(View.GONE);
            System.out.println("onCreate:A1");
            if (GetUserFuncPower("FuncA")==1) {
                txt_funcA.setVisibility(View.VISIBLE);
                AddFragment("FragmentA");
            }
            if (GetUserFuncPower("FuncB")==1) {
                txt_funcB.setVisibility(View.VISIBLE);
                AddFragment("FragmentB");
            }
            if (GetUserFuncPower("FuncC")==1) {
                txt_funcC.setVisibility(View.VISIBLE);
                AddFragment("FragmentC");
            }
            if (GetUserFuncPower("FuncG")==1) {
                txt_funcG.setVisibility(View.VISIBLE);
                AddFragment("FragmentG");
                NeedBlueTooth=true;
            } else txt_funcG.setVisibility(View.GONE);
            if (GetUserFuncPower("FuncScan")==1) {
                txt_funcScan.setVisibility(View.VISIBLE);
                AddFragment("FragmentScan");
            } else txt_funcScan.setVisibility(View.GONE);
            if (GetUserFuncPower("FuncMateSend")==1) {
                txt_funcMateSend.setVisibility(View.VISIBLE);
                AddFragment("FragmentMateSend");
            } else txt_funcMateSend.setVisibility(View.GONE);
            if (GetUserFuncPower("FuncTransProc")==1) {
                txt_funcTransProc.setVisibility(View.VISIBLE);
                AddFragment("FragmentTransProc");
            } else txt_funcTransProc.setVisibility(View.GONE);
            if (GetUserFuncPower("FuncTransQuery")==1) {
                txt_funcTransQuery.setVisibility(View.VISIBLE);
                AddFragment("FragmentTransQuery");
            } else txt_funcTransQuery.setVisibility(View.GONE);
            if (GetUserFuncPower("FuncTransScan")==1) {
                txt_funcTransScan.setVisibility(View.VISIBLE);
                AddFragment("FragmentTransScan");
            } else txt_funcTransScan.setVisibility(View.GONE);
            System.out.println("onCreate:"+1);
            //不显示提示;
            if (mFragments.size()>0) findViewById(R.id.frameHintText).setVisibility(View.GONE);
        }
        System.out.println("OnCreate---加载初始Fragment");
        loadDefaultFragment();
        System.out.println("OnCreate---打开串口");
        ExitRun=false;//进入循环;
        System.out.println(CPUID);
        if (!CPUID.toUpperCase().equals("UNKNOW")&&(CPUID.length()>0)) {

        }
        System.out.println("OnCreate---Over");

        prScanSec=System.currentTimeMillis();
        //拦截扫描事件
        scannerManager = new ScannerManager(new ScannerManager.OnScanListener() {
            @Override
            public void onResult(String code,String deviceName) {
                Log.d(TAG, "code= " + code);
                playRingtone();
                if (System.currentTimeMillis()-15000>prScanSec||AllowScan) {
                    AllowScan=false;
                    sendParamFragmentBarcode(code);
                    prScanSec= System.currentTimeMillis();
                }
                else {
                    Message message = new Message();
                    Bundle bundle=new Bundle();
                    bundle.putString("MSG","扫描太快,请稍等");
                    message.what = MSG_ErrMSG;
                    message.setData(bundle);
                    mHandler.removeMessages(message.what);
                    mHandler.sendMessage(message);
                }


            }
        },this);


    }



    public String getVersionCode(Context context)
    {
        int versionCode = 0;

        // 获取软件版本号，对应AndroidManifest.xml下android:versionCode
        try {
            versionCode = context.getPackageManager().getPackageInfo("com.bodacn.cutbed", 0).versionCode;
        } catch (PackageManager.NameNotFoundException e) {
            e.printStackTrace();

        }

        return String.valueOf(versionCode);
    }


    //获取当前时间
    public String getCurentTime(){
        SimpleDateFormat   formatter   =   new   SimpleDateFormat   ("yyyy-MM-dd HH:mm:ss");
        String   date   =   formatter.format(new   java.util.Date());
        return date;
    }
    public long getCurentSecond() throws ParseException {
        String curentTime = getCurentTime();
        SimpleDateFormat sDate = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        Date date;
        long beginTime;
        date = (Date) sDate.parse(curentTime);
        beginTime = date.getTime();
        return beginTime;
    }
    //加载需要用到的Fragment
    private boolean AddFragment(String paramFrgmtName){
        //创建Fragment;
        FragmentStruct tmpFrgmtStruct=new FragmentStruct();
        try {
            Log.d("AddFragment",paramFrgmtName+"--Start");
            tmpFrgmtStruct.frgmt=(Fragment) Class.forName(getPackageName()+"."+paramFrgmtName).newInstance();
            tmpFrgmtStruct.ident=paramFrgmtName;
            mFragments.add(tmpFrgmtStruct);
            Log.d("AddFragment",paramFrgmtName+"--Over");
            return true;
        }catch (ClassNotFoundException err){
            err.printStackTrace();
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        } catch (InstantiationException e) {
            e.printStackTrace();
        }
        return  false;//未成功加载
    }

    //获取权限,默认都有;
    private int GetUserFuncPower(String paramFunc){
        if (curUserPower.length()>0)
        {
            for (int i=0;i<curUserPower.length();i++){
                if (curUserPower.optJSONObject(i).has(paramFunc)==true)
                {
                    try {
                        return curUserPower.optJSONObject(i).getInt(paramFunc);
                    } catch (JSONException e) {
                        e.printStackTrace();
                    }
                }
            }
            return 0;
        }
        return 0;
    }

    @Override
    protected void  onStart() {
        super.onStart();

    }

    //根据顺序预加载Fragment
    private void loadDefaultFragment(){
        curFragmentIndex=-1;
        if (mFragments.size()>0) {
            FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
            Log.d("msg", "Add Fragment------------------------《预加载》");
            for (int i = mFragments.size() - 1; i >= 0; i--) {
                curFragmentIndex = i;
                Log.d("预加载", mFragments.get(curFragmentIndex).ident);
                mContent = mFragments.get(curFragmentIndex).frgmt;
                fragmentTransaction.add(R.id.mFragmentContainer, mContent);
                fragmentTransaction.hide(mContent);
            }
            //提交修改并显示;
            fragmentTransaction.show(mContent);
            fragmentTransaction.commit();

        }
    }
    //Fragment切换

    public void switchFragment(Fragment from, String toFrgmtName) {
        Fragment to=null;
        for (int i=0;i<mFragments.size();i++)
        {
            if (mFragments.get(i).ident.equals(toFrgmtName)==true)
            {
                to=mFragments.get(i).frgmt;
                curFragmentIndex=i;
                break;
            }
        }
        if ((mContent != to)&&(to!=null)) {
            mContent = to;
            FragmentTransaction transaction = fragmentManager.beginTransaction().setCustomAnimations(
                    android.R.anim.slide_in_left,android.R.anim.slide_out_right);
            if (!to.isAdded()) {    // 先判断是否被add过
                transaction.hide(from).add(R.id.mFragmentContainer, to).commit(); // 隐藏当前的fragment，add下一个到Activity中
            } else {
                transaction.hide(from).show(to).commit(); // 隐藏当前的fragment，显示下一个
            }
        }

    }

    private void initView()
    {
        txt_titleInv=findViewById(R.id.txt_titleInv);
        txt_titleInv.setOnLongClickListener(new View.OnLongClickListener() {
            @Override
            public boolean onLongClick(View view) {
                AlertDialog alertDialog = new AlertDialog.Builder(view.getContext())
                        .setTitle("系统提示").setMessage("您确定要删除所有数据表？")
                        .setPositiveButton("确定", new DialogInterface.OnClickListener() {
                            public void onClick(DialogInterface dialog, int which) {
                                dropAllTable();
                                finish();
                            }
                        }).setNeutralButton("取消",
                                new DialogInterface.OnClickListener() {
                                    public void onClick(DialogInterface dialog, int which) {
                                        return;
                                    }
                                }).create(); // 创建对话框
                alertDialog.show(); // 显示对话框
                return false;
            }
        });
        title_userNo=findViewById(R.id.title_userNo);
        title_userName=findViewById(R.id.title_userName);
        title_depart=findViewById(R.id.title_depart);
        title_logintime=findViewById(R.id.title_logintime);
        //下边栏按钮
        txt_funcA=findViewById(R.id.txt_funcA);
        txt_funcB=findViewById(R.id.txt_funcB);
        txt_funcC=findViewById(R.id.txt_funcC);
        txt_funcD=findViewById(R.id.txt_funcD);
        txt_funcE=findViewById(R.id.txt_funcE);
        txt_funcF=findViewById(R.id.txt_funcF);
        txt_funcG=findViewById(R.id.txt_funcG);
        txt_funcScan=findViewById(R.id.txt_funcScan);
        txt_funcMateSend=findViewById(R.id.txt_funcMateSend);
        txt_funcTransProc=findViewById(R.id.txt_funcTransProc);
        txt_funcTransQuery=findViewById(R.id.txt_funcTransQuery);
        txt_funcTransScan=findViewById(R.id.txt_funcTransScan);
        //设置监听;
        txt_funcA.setOnClickListener(this);
        txt_funcB.setOnClickListener(this);
        txt_funcC.setOnClickListener(this);
        txt_funcD.setOnClickListener(this);
        txt_funcE.setOnClickListener(this);
        txt_funcF.setOnClickListener(this);
        txt_funcG.setOnClickListener(this);
        txt_funcScan.setOnClickListener(this);
        txt_funcMateSend.setOnClickListener(this);
        txt_funcTransProc.setOnClickListener(this);
        txt_funcTransQuery.setOnClickListener(this);
        txt_funcTransScan.setOnClickListener(this);

        //退出
        btn_LoginUser=findViewById(R.id.btn_LoginUser);
        btn_LoginClose =findViewById(R.id.btn_LoginClose);
        btn_LoginClose.setOnClickListener(this);
        //初始提醒;
        curToast = Toast.makeText(getApplicationContext(), "", Toast.LENGTH_LONG);
        curToast.setGravity(Gravity.CENTER, 0, 0);
        //蓝牙适配器初始化;
        System.out.println("A1");
        btAdapter = BluetoothAdapter.getDefaultAdapter();
        if ((btAdapter == null)) {
            Toast.makeText(this, "本机没有找到蓝牙硬件或驱动！", Toast.LENGTH_SHORT).show();
            if (curLoginUserNo.toUpperCase().equals("CS0001")==false) {
                finish();
                return;
            }
        }
        //创建表;
        CreateDBTable();
        Cursor cur=mainDB.rawQuery("Select * from  SoftVer",null);
        if (cur.getCount()>0){
            cur.moveToFirst();
            String SoftVer=cur.getString(cur.getColumnIndex("CurSoftVer"));
            System.out.println("SoftVer:"+SoftVer);
            if (!SoftVer.equals(getVersionCode(this))){
                dropAllTable();
                CreateDBTable();
                mainDB.execSQL("update SoftVer set CurSoftVer=?",new String[]{getVersionCode(this)});
            }
        } else {
            System.out.println("SoftVer:未创建");
            mainDB.execSQL("insert into SoftVer(CurSoftVer) values(?)",new String[]{getVersionCode(this)});
            dropAllTable();
            CreateDBTable();
        }

    }


    //传递参数到MainFragment
    private void sendParamFragmentA() {
        Log.d("SendParam", "sendParamFragmentA------------------Enter;");
        if (transParamsListenerA != null) {
            Log.d("SendParam", "sendParamFragmentA------------------1;");
            transParamsListenerA.TransParams(loginParams);
            Log.d("SendParam", "sendParamFragmentA------------------2;");
        }
    }

    //传递参数到MainFragment
    private void sendParamFragmentB() {
        Log.d("SendParam", "sendParamFragmentB------------------Enter;");
        if (transParamsListenerB != null) {
            Log.d("SendParam", "sendParamFragmentB------------------1;");
            transParamsListenerB.TransParams(loginParams);
            Log.d("SendParam", "sendParamFragmentB------------------2;");
        }
    }

    //传递参数到MainFragment
    private void sendParamFragmentC() {
        Log.d("SendParam", "sendParamFragmentC------------------Enter;");
        if (transParamsListenerC != null) {
            Log.d("SendParam", "sendParamFragmentC------------------1;");
            transParamsListenerC.TransParams(loginParams);
            Log.d("SendParam", "sendParamFragmentC------------------2;");
        }
    }

    //传递参数到MainFragment
    private void sendParamFragmentScan() {
        Log.d("SendParam", "sendParamFragmentScan------------------Enter;");
        if (transParamsListenerScan != null) {
            Log.d("SendParam", "sendParamFragmentScan------------------1;");
            transParamsListenerScan.TransParams(loginParams);
            Log.d("SendParam", "sendParamFragmentScan------------------2;");
        }
    }
    //传递参数到MainFragment
    private void sendParamFragmentMateSend() {
        Log.d("SendParam", "sendParamFragmentMateSend------------------Enter;");
        if (transParamsListenerMateSend != null) {
            Log.d("SendParam", "sendParamFragmentMateSend------------------1;");
            transParamsListenerMateSend.TransParams(loginParams);
            Log.d("SendParam", "sendParamFragmentMateSend------------------2;");
        }
    }

    //传递参数到MainFragment
    private void sendParamFragmentBarcode(String paramBarcode) {
        Map<String,Object> lightParams=new HashMap<String,Object>();
        //Log.d("SendParam", "sendParamFragmentEConLight------------------Enter;");
        //Log.d("SendParam", "sendParamFragmentEConLight------------------1;");
        lightParams.clear();
        lightParams.put("ParamComm", "Barcode");
        lightParams.put("Barcode", paramBarcode);
        if (mFragments.get(curFragmentIndex).ident.equals("FragmentA"))
            transParamsListenerA.TransParams(lightParams);
        if (mFragments.get(curFragmentIndex).ident.equals("FragmentB"))
            transParamsListenerB.TransParams(lightParams);
        if (mFragments.get(curFragmentIndex).ident.equals("FragmentC"))
            transParamsListenerC.TransParams(lightParams);
        if (mFragments.get(curFragmentIndex).ident.equals("FragmentD"))
            transParamsListenerD.TransParams(lightParams);
        if (mFragments.get(curFragmentIndex).ident.equals("FragmentE"))
            transParamsListenerE.TransParams(lightParams);
        if (mFragments.get(curFragmentIndex).ident.equals("FragmentF"))
            transParamsListenerF.TransParams(lightParams);
        if (mFragments.get(curFragmentIndex).ident.equals("FragmentScan"))
            transParamsListenerScan.TransParams(lightParams);
        if (mFragments.get(curFragmentIndex).ident.equals("FragmentMateSend"))
            transParamsListenerMateSend.TransParams(lightParams);
        if (mFragments.get(curFragmentIndex).ident.equals("FragmentTransProc"))
            transParamsListenerTransProc.TransParams(lightParams);
        if (mFragments.get(curFragmentIndex).ident.equals("FragmentTransQuery"))
            transParamsListenerTransQuery.TransParams(lightParams);
        if (mFragments.get(curFragmentIndex).ident.equals("FragmentTransScan"))
            transParamsListenerTransScan.TransParams(lightParams);
    }

    //传递参数到MainFragment
    private void sendParamFragmentCWeight(String paramWeight) {
        Map<String,Object> lightParams=new HashMap<String,Object>();
        //Log.d("SendParam", "sendParamFragmentEConLight------------------Enter;");
        if (transParamsListenerC != null) {
            //Log.d("SendParam", "sendParamFragmentEConLight------------------1;");
            lightParams.clear();
            lightParams.put("ParamComm", "Weight");
            lightParams.put("Weight", paramWeight);
            transParamsListenerC.TransParams(lightParams);
            //Log.d("SendParam", "sendParamFragmentEConLight------------------2;");
        }
    }

    //传递参数到MainFragment
    private void sendParamFragmentD() {
        Log.d("SendParam", "sendParamFragmentD------------------Enter;");
        if (transParamsListenerD != null) {
            Log.d("SendParam", "sendParamFragmentD------------------1;");
            transParamsListenerD.TransParams(loginParams);
            Log.d("SendParam", "sendParamFragmentD------------------2;");
        }
    }
    //传递参数到MainFragment
    private void sendParamFragmentE() {
        Log.d("SendParam", "sendParamFragmentE------------------Enter;");
        if (transParamsListenerE != null) {
            Log.d("SendParam", "sendParamFragmentE------------------1;");
            transParamsListenerE.TransParams(loginParams);
            Log.d("SendParam", "sendParamFragmentE------------------2;");
        }
    }

    //传递参数到MainFragment
    private void sendParamFragmentF() {
        Log.d("SendParam", "sendParamFragmentF------------------Enter;");
        if (transParamsListenerF != null) {
            Log.d("SendParam", "sendParamFragmentF------------------1;");
            transParamsListenerF.TransParams(loginParams);
            Log.d("SendParam", "sendParamFragmentF------------------2;");
        }
    }
    //传递参数到MainFragment
    private void sendParamFragmentG() {
        Log.d("SendParam", "sendParamFragmentG------------------Enter;");
        if (transParamsListenerG != null) {
            Log.d("SendParam", "sendParamFragmentG------------------1;");
            transParamsListenerG.TransParams(loginParams);
            Log.d("SendParam", "sendParamFragmentG------------------2;");
        }
    }
    //传递参数到MainFragment
    private void sendParamFragmentTransProc() {
        Log.d("SendParam", "sendParamFragmentTransProc------------------Enter;");
        if (transParamsListenerTransProc != null) {
            Log.d("SendParam", "sendParamFragmentTransProc------------------1;");
            transParamsListenerTransProc.TransParams(loginParams);
            Log.d("SendParam", "sendParamFragmentTransProc------------------2;");
        }
    }
    //传递参数到MainFragment
    private void sendParamFragmentTransQuery() {
        Log.d("SendParam", "sendParamFragmentTransQuery------------------Enter;");
        if (transParamsListenerTransQuery != null) {
            Log.d("SendParam", "sendParamFragmentTransQuery------------------1;");
            transParamsListenerTransQuery.TransParams(loginParams);
            Log.d("SendParam", "sendParamFragmentTransQuery------------------2;");
        }
    }
    //传递参数到MainFragment
    private void sendParamFragmentTransScan() {
        Log.d("SendParam", "sendParamFragmentTransScan------------------Enter;");
        if (transParamsListenerTransScan != null) {
            Log.d("SendParam", "sendParamFragmentTransScan------------------1;");
            transParamsListenerTransScan.TransParams(loginParams);
            Log.d("SendParam", "sendParamFragmentTransScan------------------2;");
        }
    }

    /**
     * 定义一个Handler用于接收Fragment给Activity发出来的指令
     */
    public Handler mainHandler=new Handler(){
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            if(msg!=null){
                switch (msg.what) {
                    case getParamFragmentA:

                        break;
                    case getParamFragmentB:

                        break;
                    case getParamFragmentC:

                        break;
                    case getParamFragmentD:
                        //mViewPager.setCurrentItem(0,true);
                        break;
                    case getParamFragmentE:
                        //mViewPager.setCurrentItem(1,true);
                        break;
                    case getParamFragmentF:
                        //mViewPager.setCurrentItem(2,true);
                        break;
                    case MSG_TransRefresh2Fragment:
                        Map<String,Object> params=new HashMap<String,Object>();
                        params.put("ParamComm","RefreshDetail");
                        if (mFragments.get(curFragmentIndex).ident.equals("FragmentA")) {transParamsListenerA.TransParams(params);}
                        if (mFragments.get(curFragmentIndex).ident.equals("FragmentB")) {transParamsListenerB.TransParams(params);}
                        if (mFragments.get(curFragmentIndex).ident.equals("FragmentC")) {transParamsListenerC.TransParams(params);}
                        if (mFragments.get(curFragmentIndex).ident.equals("FragmentD")) {transParamsListenerD.TransParams(params);}
                        if (mFragments.get(curFragmentIndex).ident.equals("FragmentE")) {transParamsListenerE.TransParams(params);}
                        if (mFragments.get(curFragmentIndex).ident.equals("FragmentF")) {transParamsListenerF.TransParams(params);}
                        if (mFragments.get(curFragmentIndex).ident.equals("FragmentG")) {transParamsListenerG.TransParams(params);}
                        if (mFragments.get(curFragmentIndex).ident.equals("FragmentScan")) {transParamsListenerScan.TransParams(params);}
                        if (mFragments.get(curFragmentIndex).ident.equals("FragmentMateSend")) {transParamsListenerMateSend.TransParams(params);}
                        if (mFragments.get(curFragmentIndex).ident.equals("FragmentTransProc")) {transParamsListenerTransProc.TransParams(params);}
                        if (mFragments.get(curFragmentIndex).ident.equals("FragmentTransQuery")) {transParamsListenerTransQuery.TransParams(params);}
                        if (mFragments.get(curFragmentIndex).ident.equals("FragmentTransScan")) {transParamsListenerTransScan.TransParams(params);}

                        break;
                    default:
                        break;
                }
            }
        }
    };

    /**
     * 隐藏虚拟按键，并且全屏
     */
    protected void hideBottomUIMenu() {
        //隐藏状态栏和底部虚拟按键
        View decorView = getWindow().getDecorView();
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
            int flag = View.SYSTEM_UI_FLAG_LAYOUT_STABLE
                    | View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN
                    | View.SYSTEM_UI_FLAG_HIDE_NAVIGATION
                    | View.SYSTEM_UI_FLAG_FULLSCREEN
                    | View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY;
            decorView.setSystemUiVisibility(flag);
        }
    }
    //重置所有文本的选中状态
    public void unSelected(){
        txt_funcA.setSelected(false);
        txt_funcA.setTextColor(getResources().getColor(R.color.text_gray));
        txt_funcB.setSelected(false);
        txt_funcB.setTextColor(getResources().getColor(R.color.text_gray));
        txt_funcC.setSelected(false);
        txt_funcC.setTextColor(getResources().getColor(R.color.text_gray));
        txt_funcD.setSelected(false);
        txt_funcD.setTextColor(getResources().getColor(R.color.text_gray));
        txt_funcE.setSelected(false);
        txt_funcE.setTextColor(getResources().getColor(R.color.text_gray));
        txt_funcF.setSelected(false);
        txt_funcF.setTextColor(getResources().getColor(R.color.text_gray));
        txt_funcG.setSelected(false);
        txt_funcG.setTextColor(getResources().getColor(R.color.text_gray));
        txt_funcScan.setSelected(false);
        txt_funcScan.setTextColor(getResources().getColor(R.color.text_gray));
        txt_funcMateSend.setSelected(false);
        txt_funcMateSend.setTextColor(getResources().getColor(R.color.text_gray));
        txt_funcTransProc.setSelected(false);
        txt_funcTransProc.setTextColor(getResources().getColor(R.color.text_gray));
        txt_funcTransQuery.setSelected(false);
        txt_funcTransQuery.setTextColor(getResources().getColor(R.color.text_gray));
        txt_funcTransScan.setSelected(false);
        txt_funcTransScan.setTextColor(getResources().getColor(R.color.text_gray));
    }
    public void Selected(TextView paramBtn){
        paramBtn.setSelected(true);
        paramBtn.setTextColor(getResources().getColor(R.color.text_main));
        txt_titleInv.setText(paramBtn.getText());
    }

    // 隐藏手机键盘
    private void hideIM(View edt) {
        try {
            InputMethodManager im = (InputMethodManager) getSystemService(Activity.INPUT_METHOD_SERVICE);
            IBinder windowToken = edt.getWindowToken();
            if (windowToken != null) {
                im.hideSoftInputFromWindow(windowToken, 0);
            }
        } catch (Exception e) {

        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);

    }

    private final BroadcastReceiver mReceiver = new BroadcastReceiver()
    {
        @Override
        public void onReceive(android.content.Context context, Intent intent) {
            String action = intent.getAction();
            if (BluetoothDevice.ACTION_ACL_DISCONNECTED.equals(action))
            {
                Toast.makeText(context,"蓝牙连接已断开",Toast.LENGTH_LONG).show();
            }
        }
    };

    @Override
    public void onClick(View v) {
        hideIM(v);
        hideBottomUIMenu();
        switch (v.getId()){

            case R.id.txt_funcA:
                unSelected();
                Selected(txt_funcA);
                switchFragment(mContent, "FragmentA");
                sendParamFragmentA();
                break;
            case R.id.txt_funcB:
                unSelected();
                Selected(txt_funcB);
                switchFragment(mContent, "FragmentB");
                sendParamFragmentB();
                break;
            case R.id.txt_funcC:
                unSelected();
                Selected(txt_funcC);
                switchFragment(mContent, "FragmentC");
                sendParamFragmentC();
                break;
            case R.id.txt_funcD:
                unSelected();
                Selected(txt_funcD);
                switchFragment(mContent, "FragmentD");
                sendParamFragmentD();
                break;
            case R.id.txt_funcE:
                unSelected();
                Selected(txt_funcE);
                switchFragment(mContent, "FragmentE");
                sendParamFragmentE();
                break;
            case R.id.txt_funcF:
                unSelected();
                Selected(txt_funcF);
                switchFragment(mContent, "FragmentF");
                sendParamFragmentF();
                break;
            case R.id.txt_funcG:
                unSelected();
                Selected(txt_funcG);
                switchFragment(mContent, "FragmentG");
                sendParamFragmentG();
                break;
            case R.id.txt_funcScan:
                unSelected();
                Selected(txt_funcScan);
                switchFragment(mContent, "FragmentScan");
                sendParamFragmentScan();
                break;
            case R.id.txt_funcMateSend:
                unSelected();
                Selected(txt_funcMateSend);
                switchFragment(mContent, "FragmentMateSend");
                sendParamFragmentMateSend();
                break;
            case R.id.txt_funcTransProc:
                unSelected();
                Selected(txt_funcTransProc);
                switchFragment(mContent, "FragmentTransProc");
                sendParamFragmentTransProc();
                break;
            case R.id.txt_funcTransQuery:
                unSelected();
                Selected(txt_funcTransQuery);
                switchFragment(mContent, "FragmentTransQuery");
                sendParamFragmentTransQuery();
                break;
            case R.id.txt_funcTransScan:
                unSelected();
                Selected(txt_funcTransScan);
                switchFragment(mContent, "FragmentTransScan");
                sendParamFragmentTransScan();
                break;
            case R.id.btn_LoginClose:
                finish();//关闭当前Activity，返回上一级;
                break;
        }
    }



    //判断外部存储是否可读写
    public boolean isExternalStorageWritable() {
        String state = Environment.getExternalStorageState();
        if (Environment.MEDIA_MOUNTED.equals(state)) {
            return true;
        }
        return false;
    }





    /**
     * 复制单个文件
     * @param oldPath String 原文件路径 如：c:/fqf.txt
     * @param newPath String 复制后路径 如：f:/fqf.txt
     * @return boolean
     */
    public void copyFile(String oldPath, String newPath) {
        try {
            int bytesum = 0;
            int byteread = 0;
            File oldfile = new File(oldPath);
            if (oldfile.exists()) { //文件存在时
                InputStream inStream = new FileInputStream(oldPath); //读入原文件
                FileOutputStream fs = new FileOutputStream(newPath);
                byte[] buffer = new byte[1444];
                int length;
                while ( (byteread = inStream.read(buffer)) != -1) {
                    bytesum += byteread; //字节数 文件大小
                    System.out.println(bytesum);
                    fs.write(buffer, 0, byteread);
                }
                inStream.close();
            }
        }
        catch (Exception e) {
            System.out.println("复制单个文件操作出错");
            e.printStackTrace();

        }

    }

    /**
     * 复制整个文件夹内容
     * @param oldPath String 原文件路径 如：c:/fqf
     * @param newPath String 复制后路径 如：f:/fqf/ff
     * @return boolean
     */
    public void copyFolder(String oldPath, String newPath) {

        try {
            (new File(newPath)).mkdirs(); //如果文件夹不存在 则建立新文件夹
            File a=new File(oldPath);
            String[] file=a.list();
            File temp=null;
            for (int i = 0; i < file.length; i++) {
                if(oldPath.endsWith(File.separator)){
                    temp=new File(oldPath+file[i]);
                }
                else{
                    temp=new File(oldPath+File.separator+file[i]);
                }

                if(temp.isFile()){
                    FileInputStream input = new FileInputStream(temp);
                    FileOutputStream output = new FileOutputStream(newPath + "/" +
                            (temp.getName()).toString());
                    byte[] b = new byte[1024 * 5];
                    int len;
                    while ( (len = input.read(b)) != -1) {
                        output.write(b, 0, len);
                    }
                    output.flush();
                    output.close();
                    input.close();
                }
                if(temp.isDirectory()){//如果是子文件夹
                    copyFolder(oldPath+"/"+file[i],newPath+"/"+file[i]);
                }
            }
        }
        catch (Exception e) {
            System.out.println("复制整个文件夹内容操作出错");
            e.printStackTrace();

        }

    }

    //插放音乐;
    private void playRingtone(){
        Uri notification = Uri.parse("android.resource://"+this.getPackageName()+"/"+R.raw.scan);
        Ringtone r = RingtoneManager.getRingtone(this, notification);
        r.play();

    }

    @Override
    protected void onPause() {
        super.onPause();
        Log.d("系统提示","OnPause");
    }

    @Override
    protected void onResume() {
        super.onResume();
        Log.d("系统提示","onResume");
        hideBottomUIMenu();
        System.out.println("onResume--Start");
        /*增减功能时这里要同步修改*/
        if (curFragmentIndex>-1){
            System.out.println("curFragmentIndex:"+curFragmentIndex);
            if (mFragments.get(curFragmentIndex).ident.equals("FragmentA")) {Selected(txt_funcA);sendParamFragmentA();}
            if (mFragments.get(curFragmentIndex).ident.equals("FragmentB")) {Selected(txt_funcB);sendParamFragmentB();}
            if (mFragments.get(curFragmentIndex).ident.equals("FragmentC")) {Selected(txt_funcC);sendParamFragmentC();}
            if (mFragments.get(curFragmentIndex).ident.equals("FragmentD")) {Selected(txt_funcD);sendParamFragmentD();}
            if (mFragments.get(curFragmentIndex).ident.equals("FragmentE")) {Selected(txt_funcE);sendParamFragmentE();}
            if (mFragments.get(curFragmentIndex).ident.equals("FragmentF")) {Selected(txt_funcF);sendParamFragmentF();}
            if (mFragments.get(curFragmentIndex).ident.equals("FragmentG")) {Selected(txt_funcG);sendParamFragmentG();}
            if (mFragments.get(curFragmentIndex).ident.equals("FragmentMateSend")) {Selected(txt_funcG);sendParamFragmentG();}
            if (mFragments.get(curFragmentIndex).ident.equals("FragmentTransProc")) {Selected(txt_funcTransProc);sendParamFragmentTransProc();}
            if (mFragments.get(curFragmentIndex).ident.equals("FragmentTransQuery")) {Selected(txt_funcTransQuery);sendParamFragmentTransQuery();}
            if (mFragments.get(curFragmentIndex).ident.equals("FragmentTransScan")) {Selected(txt_funcTransScan);sendParamFragmentTransScan();}

        }
        System.out.println("onResume--Over");
        if (!CPUID.toUpperCase().equals("UNKNOW")&&(CPUID.length()>0)) {

        }
        startTimer();

    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        Log.d("调试","onDestroy");
        ExitRun=true;
        receiveFlag=false;
        mHandler.removeCallbacksAndMessages(null);
        if (textToSpeech!=null){
            textToSpeech.stop();
            textToSpeech.shutdown();
        }
        stopTimer();
        Log.d("msg","MainActivity OnDestroy------------------------");


    }

    @Override
    protected void onRestart() {
        super.onRestart();
        Log.d("系统提示","onRestart");
        if (!CPUID.toUpperCase().equals("UNKNOW")&&(CPUID.length()>0)) {

        }
    }
}
